from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from api import models
from django.db.models import Q
import datetime
from api.plugins import process_server_info


class ServerView(APIView):
    def get(self, request, *args, **kwargs):
        """ 返回今日未采集的服务器列表 """
        today = datetime.datetime.today()
        queryset = models.Server.objects.filter(status=1).filter(
            Q(last_check_date__isnull=True) | Q(last_check_date__lt=today)).values('host_name')
        host_list = [item['host_name'] for item in queryset]
        return Response(host_list)

    def post(self, request, *args, **kwargs):
        # 1. 获取到用户提交资产信息
        # 2. 保存到数据库（表关系）
        host_name = request.data.get('hostname')
        server_object = models.Server.objects.filter(host_name=host_name).first()
        if not server_object:
            return Response('主机不存在')
        process_server_info(request.data, server_object)

        # 今日已经采集
        server_object.last_date = datetime.datetime.today()
        server_object.save()

        return Response('发送成功')
